<template>
  <div class="register-container">
    <el-card class="register-card">
      <div class="logo-container">
        <img src="../assets/logo.png" alt="Logo" class="logo">
        <h2>MBTI职业性格测试系统</h2>
      </div>
      
      <el-form
        ref="formRef"
        :model="registerForm"
        :rules="rules"
        label-position="top"
      >
        <el-form-item label="姓名" prop="fullName">
          <el-input
            v-model="registerForm.fullName"
            placeholder="请输入姓名"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item label="用户类型" prop="userType">
          <el-radio-group v-model="registerForm.userType">
            <el-radio label="STUDENT">学生</el-radio>
            <el-radio label="TEACHER">教师</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="registerForm.userType === 'STUDENT'"
          label="学号"
          prop="usercode"
        >
          <el-input
            v-model="registerForm.usercode"
            placeholder="请输入学号"
            prefix-icon="Document"
          />
        </el-form-item>

        <template v-if="registerForm.userType === 'STUDENT'">
          <el-form-item label="学校" prop="schoolId">
            <el-select 
              v-model="registerForm.schoolId" 
              placeholder="请选择学校"
              @change="handleSchoolChange"
              style="width: 100%"
            >
              <el-option 
                v-for="school in schools" 
                :key="school.orgId" 
                :label="school.name" 
                :value="school.orgId" 
              />
            </el-select>
          </el-form-item>

          <el-form-item label="学院" prop="departmentId">
            <el-select 
              v-model="registerForm.departmentId" 
              placeholder="请选择学院"
              @change="handleDepartmentChange"
              style="width: 100%"
              :disabled="!registerForm.schoolId"
            >
              <el-option 
                v-for="dept in departments" 
                :key="dept.orgId" 
                :label="dept.name" 
                :value="dept.orgId" 
              />
            </el-select>
          </el-form-item>

          <el-form-item label="专业" prop="majorId">
            <el-select 
              v-model="registerForm.majorId" 
              placeholder="请选择专业"
              @change="handleMajorChange"
              style="width: 100%"
              :disabled="!registerForm.departmentId"
            >
              <el-option 
                v-for="major in majors" 
                :key="major.orgId" 
                :label="major.name" 
                :value="major.orgId" 
              />
            </el-select>
          </el-form-item>

          <el-form-item label="班级" prop="orgId">
            <el-select 
              v-model="registerForm.orgId" 
              placeholder="请选择班级"
              style="width: 100%"
              :disabled="!registerForm.majorId"
            >
              <el-option 
                v-for="cls in classes" 
                :key="cls.orgId" 
                :label="cls.name" 
                :value="cls.orgId" 
              />
            </el-select>
          </el-form-item>
        </template>

        <el-form-item
          v-if="registerForm.userType === 'TEACHER'"
          label="教师工号"
          prop="usercode"
        >
          <el-input
            v-model="registerForm.usercode"
            placeholder="请输入教师工号"
            prefix-icon="Document"
          />
        </el-form-item>

        <!-- 教师权限选择 -->
        <el-form-item
          v-if="registerForm.userType === 'TEACHER'"
          label="申请权限"
          prop="requestedRole"
        >
          <el-select 
            v-model="registerForm.requestedRole" 
            placeholder="请选择申请的权限"
            style="width: 100%"
          >
            <el-option label="普通教师" value="TEACHER" />
            <el-option label="班级管理员" value="CLASS_ADMIN" />
            <el-option label="系级管理员" value="MAJOR_ADMIN" />
            <el-option label="院级管理员" value="DEPARTMENT_ADMIN" />
          </el-select>
          <div class="role-info">
            <p v-if="registerForm.requestedRole === 'TEACHER' || registerForm.requestedRole === 'CLASS_ADMIN'">
              需要系级以上管理员审批
            </p>
            <p v-else-if="registerForm.requestedRole === 'MAJOR_ADMIN'">
              需要院级以上管理员审批
            </p>
            <p v-else-if="registerForm.requestedRole === 'DEPARTMENT_ADMIN'">
              需要校级以上管理员审批
            </p>
          </div>
        </el-form-item>

        <!-- 教师所属组织选择 -->
        <template v-if="registerForm.userType === 'TEACHER'">
          <el-form-item label="学校" prop="schoolId">
            <el-select 
              v-model="registerForm.schoolId" 
              placeholder="请选择学校"
              @change="handleSchoolChange"
              style="width: 100%"
            >
              <el-option 
                v-for="school in schools" 
                :key="school.orgId" 
                :label="school.name" 
                :value="school.orgId" 
              />
            </el-select>
          </el-form-item>

          <el-form-item 
            label="学院" 
            prop="departmentId"
            v-if="showDepartmentSelect"
          >
            <el-select 
              v-model="registerForm.departmentId" 
              placeholder="请选择学院"
              @change="handleDepartmentChange"
              style="width: 100%"
              :disabled="!registerForm.schoolId"
            >
              <el-option 
                v-for="dept in departments" 
                :key="dept.orgId" 
                :label="dept.name" 
                :value="dept.orgId" 
              />
            </el-select>
          </el-form-item>

          <el-form-item 
            label="专业" 
            prop="majorId"
            v-if="showMajorSelect"
          >
            <el-select 
              v-model="registerForm.majorId" 
              placeholder="请选择专业"
              @change="handleMajorChange"
              style="width: 100%"
              :disabled="!registerForm.departmentId"
            >
              <el-option 
                v-for="major in majors" 
                :key="major.orgId" 
                :label="major.name" 
                :value="major.orgId" 
              />
            </el-select>
          </el-form-item>

          <el-form-item 
            label="班级" 
            prop="classId"
            v-if="showClassSelect"
          >
            <el-select 
              v-model="registerForm.orgId" 
              placeholder="请选择班级"
              style="width: 100%"
              :disabled="!registerForm.majorId"
            >
              <el-option 
                v-for="cls in classes" 
                :key="cls.orgId" 
                :label="cls.name" 
                :value="cls.orgId" 
              />
            </el-select>
          </el-form-item>
        </template>

        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            prefix-icon="Message"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="register-button" @click="handleRegister">
            注册
          </el-button>
        </el-form-item>

        <div class="login-link">
          已有账号？
          <router-link to="/login">立即登录</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'RegisterPage'
}
</script>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

const router = useRouter()
const userStore = useUserStore()

const registerForm = ref({
  fullName: '',
  password: '',
  confirmPassword: '',
  email: '',
  userType: 'STUDENT',
  usercode: '',
  schoolId: null,
  departmentId: null,
  majorId: null,
  orgId: null,
  requestedRole: 'TEACHER' // 默认为普通教师
})

// 组织结构数据
const departments = ref([])
const majors = ref([])
const classes = ref([])
const schools = ref([])

// 在组件挂载时获取学校列表
onMounted(async () => {
  try {
    await loadSchools()
  } catch (error) {
    console.error('获取学校列表失败:', error)
    ElMessage.error('获取学校列表失败')
  }
})

// 获取学校数据
const loadSchools = async () => {
  try {
    const response = await request.get('/organizations/type/SCHOOL')
    if (response && response.data) {
      // 确保返回的数据是数组
      schools.value = Array.isArray(response.data) ? response.data : [];
    }
  } catch (error) {
    console.error('获取学校数据失败:', error)
    throw error
  }
}

// 当选择学校后，获取该学校下的学院
const handleSchoolChange = async () => {
  registerForm.value.departmentId = null
  registerForm.value.majorId = null
  registerForm.value.orgId = null
  departments.value = []
  majors.value = []
  classes.value = []
  
  if (!registerForm.value.schoolId) return
  
  try {
    const response = await request.get(`/organizations/parent/${registerForm.value.schoolId}/type/DEPARTMENT`)
    if (response && response.data) {
      // 确保返回的数据是数组
      departments.value = Array.isArray(response.data) ? response.data : [];
    }
  } catch (error) {
    console.error('获取学院数据失败:', error)
    ElMessage.error('获取学院数据失败')
  }
}

// 当选择学院后，获取该学院下的专业
const handleDepartmentChange = async () => {
  registerForm.value.majorId = null
  registerForm.value.orgId = null
  majors.value = []
  classes.value = []
  
  if (!registerForm.value.departmentId) return
  
  try {
    const response = await request.get(`/organizations/parent/${registerForm.value.departmentId}/type/MAJOR`)
    if (response && response.data) {
      // 确保返回的数据是数组
      majors.value = Array.isArray(response.data) ? response.data : [];
    }
  } catch (error) {
    console.error('获取专业数据失败:', error)
    ElMessage.error('获取专业数据失败')
  }
}

// 当选择专业后，获取该专业下的班级
const handleMajorChange = async () => {
  registerForm.value.orgId = null
  classes.value = []
  
  if (!registerForm.value.majorId) return
  
  try {
    const response = await request.get(`/organizations/parent/${registerForm.value.majorId}/type/CLASS`)
    if (response && response.data) {
      // 确保返回的数据是数组
      classes.value = Array.isArray(response.data) ? response.data : [];
    }
  } catch (error) {
    console.error('获取班级数据失败:', error)
    ElMessage.error('获取班级数据失败')
  }
}

// 表单验证规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    // 如果确认密码已经输入，则重新验证确认密码
    if (registerForm.value.confirmPassword !== '') {
      // 使用 nextTick 确保在下一个 DOM 更新周期再验证
      // 这样可以避免在当前验证过程中再次触发验证导致的错误
      setTimeout(() => {
        if (formRef.value) {
          formRef.value.validateField('confirmPassword')
        }
      }, 0)
    }
    callback()
  }
}

const validatePassConfirm = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.value.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 验证邮箱是否存在
const validateEmail = async (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入邮箱'))
  }
  
  try {
    const response = await request.get(`/users/check-email?email=${value}`)
    if (response && response.data === true) {
      return callback(new Error('该邮箱已被注册'))
    }
    callback()
  } catch (error) {
    console.error('验证邮箱失败:', error)
    callback(new Error('验证邮箱时出错'))
  }
}

// 验证用户码是否存在
const validateUsercode = async (rule, value, callback) => {
  if (!value) {
    return callback(new Error(registerForm.value.userType === 'STUDENT' ? '请输入学号' : '请输入教师工号'))
  }
  
  try {
    const response = await request.get(`/users/check-usercode?usercode=${value}`)
    if (response && response.data === true) {
      return callback(new Error('该学号/教师工号已被注册'))
    }
    callback()
  } catch (error) {
    console.error('验证用户码失败:', error)
    callback(new Error('验证用户码时出错'))
  }
}

const validateOrgId = (rule, value, callback) => {
  // 如果是学生，班级必选
  if (registerForm.value.userType === 'STUDENT' && !value) {
    return callback(new Error('请选择班级'));
  }
  
  // 如果是教师，根据申请的角色判断
  if (registerForm.value.userType === 'TEACHER') {
    if (registerForm.value.requestedRole === 'DEPARTMENT_ADMIN' && !registerForm.value.departmentId) {
      return callback(new Error('请选择学院'));
    }
    if ((registerForm.value.requestedRole === 'MAJOR_ADMIN' || registerForm.value.requestedRole === 'TEACHER') && !registerForm.value.majorId) {
      return callback(new Error('请选择专业'));
    }
    if (registerForm.value.requestedRole === 'CLASS_ADMIN' && !value) {
      return callback(new Error('请选择班级'));
    }
  }
  
  callback();
};

const rules = {
  fullName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  usercode: [
    { required: true, message: '请输入学号/教师工号', trigger: 'blur' },
    { validator: validateUsercode, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePassConfirm, trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  schoolId: [
    { required: true, message: '请选择学校', trigger: 'change' }
  ],
  departmentId: [
    { 
      required: true, 
      message: '请选择学院', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (showDepartmentSelect.value && !value) {
          return callback(new Error('请选择学院'));
        }
        callback();
      }
    }
  ],
  majorId: [
    { 
      required: true, 
      message: '请选择专业', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (showMajorSelect.value && !value) {
          return callback(new Error('请选择专业'));
        }
        callback();
      }
    }
  ],
  orgId: [
    { validator: validateOrgId, trigger: 'change' }
  ],
  requestedRole: [
    { 
      required: true, 
      message: '请选择申请的权限', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (registerForm.value.userType === 'TEACHER' && !value) {
          return callback(new Error('请选择申请的权限'));
        }
        callback();
      }
    }
  ]
}

const formRef = ref(null)

// 根据所选角色决定显示哪些组织层级选择器
const showDepartmentSelect = computed(() => {
  return registerForm.value.userType === 'STUDENT' || 
         (registerForm.value.userType === 'TEACHER');
});

const showMajorSelect = computed(() => {
  return registerForm.value.userType === 'STUDENT' || 
         (registerForm.value.userType === 'TEACHER' && 
          (registerForm.value.requestedRole === 'MAJOR_ADMIN' || 
           registerForm.value.requestedRole === 'CLASS_ADMIN' ||
           registerForm.value.requestedRole === 'TEACHER'));
});

const showClassSelect = computed(() => {
  return registerForm.value.userType === 'STUDENT' || 
         (registerForm.value.userType === 'TEACHER' && 
          registerForm.value.requestedRole === 'CLASS_ADMIN');
});

// 监听requestedRole变化，重置相关字段
watch(() => registerForm.value.requestedRole, (newRole) => {
  // 重置不需要的字段
  if (newRole === 'DEPARTMENT_ADMIN') {
    registerForm.value.majorId = null;
    registerForm.value.orgId = registerForm.value.departmentId; // 设置组织ID为学院ID
  } else if (newRole === 'MAJOR_ADMIN' || newRole === 'TEACHER') {
    registerForm.value.orgId = registerForm.value.majorId; // 设置组织ID为专业ID
  }
  // CLASS_ADMIN 不需要特殊处理，因为它需要选择到班级
});

const handleRegister = async () => {
  if (!formRef.value) return
  
  // 先检查密码是否一致
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  
  try {
    await formRef.value.validate()
    
    // 根据角色设置最终的组织ID
    if (registerForm.value.userType === 'TEACHER') {
      if (registerForm.value.requestedRole === 'DEPARTMENT_ADMIN') {
        registerForm.value.orgId = registerForm.value.departmentId;
      } else if (registerForm.value.requestedRole === 'MAJOR_ADMIN' || registerForm.value.requestedRole === 'TEACHER') {
        registerForm.value.orgId = registerForm.value.majorId;
      }
      // CLASS_ADMIN 的 orgId 已经设置为班级ID
    }
    
    // 构建注册数据
    const registerData = {
      fullName: registerForm.value.fullName,
      usercode: registerForm.value.usercode,
      email: registerForm.value.email,
      password: registerForm.value.password,
      userType: registerForm.value.userType,
      orgId: registerForm.value.orgId || 0,
      requestedRole: registerForm.value.userType === 'TEACHER' ? registerForm.value.requestedRole : null
    }
    
    const response = await userStore.register(registerData)
    
    // 检查响应结构
    console.log('Register response:', response)
    
    // 根据用户类型展示不同的成功信息
    if (registerForm.value.userType === 'TEACHER') {
      ElMessage.success('教师账号注册成功，等待管理员审核')
    } else {
      ElMessage.success('注册成功')
    }
    
    // 跳转到登录页
    router.push('/login')
  } catch (error) {
    console.error('Register error:', error)
    ElMessage.error(error.response?.message || error.message || '注册失败')
  }
}
</script>

<style scoped>
.register-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.register-card {
  width: 400px;
  padding: 20px;
}

.logo-container {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 100px;
  height: 100px;
  margin-bottom: 10px;
}

.register-button {
  width: 100%;
}

.login-link {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
}

.login-link a {
  color: #409eff;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}

.role-info {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}
</style> 